import { Button, Form, Input, Cascader, Select, Radio, FormInstance } from 'antd';
import { useEffect, useState } from 'react'
import { message, Upload } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { useNavigate } from 'react-router';
import { useLocation } from 'react-router-dom';
import React from 'react';
import { userinfotype, buildingList, HouseList, userinfoAdd } from '../../apis/userInfo/index';

const UserInfoAdd = (_props: any): JSX.Element => {
    const formRef = React.useRef<FormInstance>(null);
    const navigate = useNavigate()
    const [useradd, setUserAdd] = useState(
        {
            photo: '',
            buildingid: 0,
            houseid: 0,
            name: '',
            sex: 0,
            nation: '',
            usernative: '',
            cardid: '',
            mobile: 0,
            usertype: 1
        }
    )
    const [imageUrl, setImageUrl] = useState<string>();
    const { state } = useLocation()
    console.log('stste', state);
    const [loading, setLoading] = useState(false);

    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };
    const getBase64 = (img: RcFile, callback: (url: string) => void) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);
    };
    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            // setUserAdd({ ...useradd, photo: info.file.name })
            return;
        }
        // console.log(info.file, 'info.file');
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj as RcFile, (url) => {

                setLoading(false);
                setImageUrl(url)
            });
            if (info.file.response.errCode === 10000) {
                setUserAdd({ ...useradd, photo: info.file.response.data })
            }
        }

    };
    const [options, setOptions]: any = useState([])
    const getBuilding = async () => {
        let res = await buildingList()
        // console.log(res, 'res');
        setOptions(res.data.list)
    }
    const [typeList, setTypeList]: any = useState([])
    const getTypeList = async () => {
        let res = await userinfotype()
        // console.log('typename', res);
        setTypeList(res.data.list)
    }
    // const [messageApi, contextHolder] = message.useMessage();
    const onFinish = async (values: any) => {
        // console.log('Success:', values);
        values.buildingid = values.buildingid.pop()
        if (values.photo) {
            if (values.photo.file.response.errCode == 10000) {
                values.photo = values.photo.file.response.data
            }
        }
        if (!state) {
            let res: any = await userinfoAdd(values)
            // console.log('添加', res);
            if (res.errCode == 10000) {
                message.open({
                    type: 'success',
                    content: '添加成功',
                });
                navigate('/home/userinfo')
            } else {
                message.open({
                    type: 'error',
                    content: res.errMsg,
                });
            }
        } else {
            let res: any = await userinfoAdd({ ...values, id: state.record.id })
            console.log('修改', res);
            if (res.errCode == 10000) {
                message.open({
                    type: 'success',
                    content: '修改成功',
                });
                navigate('/home/userinfo')
            }
        }
    };

    const imgUrl = process.env.REACT_APP_IMG_URL
    const upImgUrl = process.env.REACT_APP_UP_IMG_URL
    useEffect(() => {
        getBuilding()
        getTypeList()
        if (state) {
            form.setFieldsValue(state.record)
            setImageUrl(imgUrl + state.record.photo)
        }

    }, [])
    const [houseid, setHouse] = useState([])
    const onchange = async (value: any) => {
        // console.log(value);
        let id = value.slice(-2)[0]
        let res = await HouseList({ buildingid: id })
        // console.log('房间', res);
        setHouse(res.data.list)
    };
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    const [form] = Form.useForm();
    const onReset = () => {
        formRef.current?.resetFields();
        setImageUrl('')
    };
    let fiel = {
        label: 'name',
        value: 'id',
        children: 'children'
    }
    return <div className="boxAdd">
        <h2>{!state ? '添加居民' : '修改居民'}</h2>
        <Form
            name="basic"
            form={form}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            ref={formRef}
            autoComplete="off"
        >
            <Form.Item
                label="头像"
                name="photo"
                rules={[{ required: true, message: '请上传头像' }]}
                className='image'
            >
                <Upload
                    name="file"
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    action={upImgUrl}
                    beforeUpload={beforeUpload}
                    headers={{ Authorization: sessionStorage.getItem('token') || '' }}
                    onChange={handleChange}
                >
                    {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                </Upload>
            </Form.Item>
            <Form.Item
                label="楼栋"
                name="buildingid"
                rules={[{ required: true, message: '请选择楼栋' }]}
            >
                <Cascader options={options} onChange={onchange} fieldNames={fiel} placeholder="请选择楼栋" style={{ width: "200px", marginLeft: "26px" }} />
            </Form.Item>
            <Form.Item
                label="房间号"
                name="houseid"
                rules={[{ required: true, message: '请选择房间号' }]}
            >
                <Select allowClear placeholder="请选择" style={{ width: "200px", marginLeft: "13px" }}>
                    {
                        houseid.map((item: any) => {
                            return (
                                <Select.Option key={item.id} value={item.id} label={item.building}>
                                    {item.building}
                                </Select.Option>
                            )
                        })
                    }
                </Select>
            </Form.Item>
            <Form.Item
                label="姓名"
                name="name"
                rules={[{ required: true, message: '请输入姓名' }]}
            >
                <Input style={{ width: "200px", marginLeft: "26px" }} />
            </Form.Item>
            <Form.Item
                label="性别"
                name="sex"
                rules={[{ required: true, message: '请选择性别' }]}
            >
                <Radio.Group value={useradd.sex} style={{ width: "200px", marginLeft: "26px" }}>
                    <Radio value={1}>男</Radio>
                    <Radio value={0}>女</Radio>
                </Radio.Group>
            </Form.Item>
            <Form.Item
                label="民族"
                name="nation"
                rules={[{ required: true, message: '请输入民族' }]}
            >
                <Input style={{ width: "200px", marginLeft: "26px" }} />
            </Form.Item>
            <Form.Item
                label="籍贯"
                name="usernative"
                rules={[{ required: true, message: '请输入籍贯' }]}
            >
                <Input style={{ width: "200px", marginLeft: "26px" }} />
            </Form.Item>
            <Form.Item
                label="身份证号"
                name="cardid"
                rules={[{ required: true, message: '请输入身份证号' }]}
            >
                <Input style={{ width: "200px" }} />
            </Form.Item>
            <Form.Item
                label="联系电话"
                name="mobile"
                rules={[{ required: true, message: '请输入联系电话' }]}
            >
                <Input type='number' style={{ width: "200px" }} />
            </Form.Item>
            <Form.Item
                label="住户类型"
                name="usertype"
                rules={[{ required: true, message: '请选择住户类型' }]}
            >
                <Select allowClear placeholder="请选择" style={{ width: "200px" }}>
                    {
                        typeList.map((item: any) => {
                            return (
                                <Select.Option key={item.id} value={item.id} label={item.name}>
                                    {item.name}
                                </Select.Option>
                            )
                        })
                    }
                </Select>
            </Form.Item>
            <Form.Item>
                <Button type='primary' htmlType="submit">{!state ? '添加' : '修改'}</Button>
                <Button type='primary' danger style={{ marginLeft: '10px' }} htmlType="button" onClick={onReset}>重置</Button>
            </Form.Item>
        </Form>
    </div>
}
export default UserInfoAdd